﻿using System;
using ufida.u9.ait.openbp;
using ufida.u9.ait.openbp.Proxy;
using UFIDA.U9.SCM.SM.SOUIModel;
using UFSoft.UBF.UI.ControlModel;
using UFSoft.UBF.UI.IView;
using UFSoft.UBF.UI.WebControlAdapter;

namespace UFIDA.U9.Cust.Cli.PlugUI
{
    public class ZDSOMainUIFormWebPart : UFSoft.UBF.UI.Custom.ExtendedPartBase
    {
        private StandardSOMainUIFormWebPart part;
        //配置文件XX.config文件拷贝到portal下，dll文件放置到portal/UILib下
        //配置文件以WebPartExtend开头
        public override void AfterInit(IPart Part, EventArgs args)
        {
            //首先调用原来的事件
            base.AfterInit(Part, args);
            part = Part as StandardSOMainUIFormWebPart;

            if (part == null)
                return;

            //2.Card里面增加按钮
            //设置按钮在容器中的位置
            #region 2.Card里面增加按钮
            IUFCard card = (IUFCard)part.GetUFControlByName(part.TopLevelContainer, "Card0");
            IUFButton btnCreateFAS;
            btnCreateFAS = new UFWebButtonAdapter();
            btnCreateFAS.Text = "生成FAS料号";
            btnCreateFAS.ID = "btnCreateFAS";
            btnCreateFAS.AutoPostBack = true;
            card.Controls.Add(btnCreateFAS);
            btnCreateFAS.Click += new EventHandler(BtnCreateFAS_Click);
            CommonFunction.Layout(card, btnCreateFAS, 18, 0);   //一般为从左往右按钮个数乘以2
            #endregion
        }

        private void BtnCreateFAS_Click(object sender, EventArgs e)
        {
            SORecord sorec = this.part.Model.SO.FocusedRecord;
            
            //清除感叹号
            sorec.ClearErrorMessage();
            
            try
            {
                if (sorec.ID <= 0)
                {
                    throw new Exception("单据尚未保存");
                }

                //if (IsChanged())
                //{
                //    this.part.BtnSave_Click(sender, e);
                //}

                //单据保存
                this.part.BtnSave_Click(sender, e);
                //调用BP
                SOCreateFASItemProxy bp = new SOCreateFASItemProxy();
                bp.ID = sorec.ID;
                bp.Do();
                //刷新界面
                this.part.Action.NavigateAction.Refresh(null);

            }
            catch (Exception ex)
            {
                //前端报错,方法支持具体字段
                UIHelper.SetErrorMsg(this.part,this.part.Model.SO.FocusedRecord, null, ex.Message);
            }            
        }

        /// <summary>
        /// 判断单据是否修改
        /// </summary>
        /// <returns></returns>
        private bool IsChanged()
        {
            SORecord mainRec = this.part.Model.SO.FocusedRecord;
            if (mainRec != null && mainRec.IsDataChanged)
                return true;

            UFSoft.UBF.UI.MD.Runtime.IUIRecordCollection lineRecs = this.part.Model.SO_SOLines.Records;
            foreach(var line in lineRecs)
            {
                if (line.IsDataChanged) return true;
            }

            return false;
        }
    }
}
